var express = require('express');
var router = express.Router();
let upload = require('../util/multer/index')
var moment = require('moment');
var FastScanner = require('fastscan');
const rp = require('request-promise-native');
const svgCaptcha = require('svg-captcha');

let { isgender, FormatData, urlf2z, getBase64, setBase64 } = require('../util.js');
let { getSwiperList, register, isUser, getInfoList, infoDetail, isaddPraise, fabulousNum, delPraise, addPraise, addInfoComm,
  getInfoComm, commNum, getKnowList, isCollection, isaaddFollow, delFollow, addFollow, knowDetail, getKnowComm, addKnowComm,
  addInfo, getLikeList, getCommList, getSensitiveAll, getCollectionList
} = require('../mysql/users')
/**
 * 所有关于用户的请求接口
 */
const methodsToken = [
  '/addPraise',
  '/addInfoComm',
  '/addFollow',
  '/addInfo',
  '/getLikeList',
  '/getCommList',
  '/getCollectionList'
];
router.post("*", (req, res, next) => {
  // 判断token是否存在
  if (methodsToken.indexOf(req.url) >= 0) {
    // 获取用户token
    let userToken = req.headers.token;
    if (!userToken) {
      return res.json({
        code: 0,
        data: "请先登录"
      });
    } else {
      let userId = setBase64(userToken);
      req.body.userId = userId;
    }
  } else {
    let userToken = req.headers.token;
    if (userToken) {
      let userId = setBase64(userToken);
      req.body.userId = userId;
    }
  }
  next();
})
router.get('/svg', (req, res) => {
  const cap = svgCaptcha.create({
    // 翻转颜色
    inverse: false,
    // 字体大小
    fontSize: 36,
    // 噪声线条数
    noise: 3,
    // 宽度
    width: 80,
    // 高度
    height: 30,
  });
  if (req.session.user != '') {
    req.session.captcha = cap.text; // session 存储验证码数值
  }
  res.type('svg'); // 响应的类型
  res.send(cap.data)
})
/**
 * 返回首页轮播图数据
 */
router.get('/getSwiperList', async (req, res, next) => {
  let data = await getSwiperList();
  res.json({
    code: 1,
    data
  })
})
/**
 * 用户注册
 */
router.post('/register', async (req, res, next) => {
  let { userPhone, userPass, code, userName, userSex, userUrl } = req.body
  console.log(req.session)
  try {
    const sessionCaptcha = req.session.captcha.toLowerCase();
    code = String(code).toLowerCase()
    if (sessionCaptcha != code) {
      return res.json({
        flog: 0,
        data: '验证码不正确'
      });
    }
  } catch (error) {
    return res.json({
      flog: 0,
      data: '验证码不正确'
    });
  }
  let isUserInfo = await isUser({
    userPhone: userPhone
  })

  if (isUserInfo.length) {
    res.json({
      code: 0,
      data: {
        msg: '用户已经存在'
      }
    })
  } else {
    await register({
      userPhone, userPass, userName, userSex, userUrl
    })
    res.json({
      code: 1,
      data: {
        msg: '用户注册成功'
      }
    })
  }
})
/**
 * 用户登录
 */
router.post('/login', async (req, res, next) => {
  let { userPhone, userPass } = req.body
  let isUserInfo = await isUser({
    userPhone, userPass
  })
  if (isUserInfo.length) {
    res.json({
      code: 1,
      data: {
        Token: getBase64(isUserInfo[0].userId),
        userInfo: isUserInfo,
        msg: '登陆成功'
      }
    })
  } else {
    res.json({
      code: 0,
      data: {
        msg: '帐号或者密码错误'
      }
    })
  }
})
/**
 * 获取帖子
 */
router.post('/getInfoList', async (req, res, next) => {
  let { page, limit, infoTitle } = req.body;
  var num = (page - 1) * limit;
  let data = await getInfoList(num, limit, {
    infoTitle: infoTitle
  });

  let asyncList = data.data.map(item => {
    return new Promise(async (res, rej) => {
      let f_num = await fabulousNum({
        infoId: item.infoId
      })
      let c_Num = await commNum({
        infoId: item.infoId
      })
      item.FabulousNum = f_num
      item.c_Num = c_Num
      res()
    })
  })

  await Promise.all(asyncList)

  res.json({
    code: 1,
    data: FormatData(data.data, {
      infoImgList: 'json',
      infoTime: 'date'
    }),
    msg: '获取成功'
  })
})
/**
 * 获取帖子详情
 */
router.post('/infoDetail', async (req, res, next) => {
  let { infoId, userId } = req.body;
  let data = await infoDetail(infoId)
  let num = await fabulousNum({
    infoId
  })
  data.FabulousNum = num
  if (userId) {
    let Praise = await isaddPraise({
      userId, infoId
    })
    data.isFabulous = Boolean(Praise.length)
  } else {
    data.isFabulous = false
  }
  res.json({
    code: 1,
    data: FormatData(data, {
      infoImgList: 'json',
      infoTime: 'date'
    }),
    msg: '获取成功'
  })
})
/**
 * 帖子点赞
 */
router.post('/addPraise', async (req, res, next) => {
  let { userId, infoId } = req.body;
  let flog = await isaddPraise({
    userId, infoId
  })
  if (flog.length) {
    await delPraise(flog[0].praiseId)
    res.json({
      code: 1,
      data: {
        info: "取消点赞成功",
        flog: 0
      }
    })
  } else {
    await addPraise({
      userId, infoId
    })
    res.json({
      code: 1,
      data: {
        info: "点赞成功",
        flog: 0
      }
    })
  }
})
/**
 * 用户评论
 */
router.post('/addInfoComm', async (req, res, next) => {
  let { content, userId, infoId } = req.body
  let data = await addInfoComm({
    userId, infoId, comm: content
  });
  res.json({
    code: 1,
    data: data,
    msg: "添加成功"
  })
})
/**
 * 获取帖子评论
 */
router.post('/getInfoComm', async (req, res, next) => {
  let { page, limit, id } = req.body;
  var num = (page - 1) * limit;
  let data = await getInfoComm(num, limit, {
    infoId: id
  })
  res.json({
    code: 1,
    data: FormatData(data.data, {
      time: 'date'
    }),
    msg: '获取成功'
  })
})
/**
 * 获取文章信息
 */
router.post('/getKnowList', async (req, res, next) => {
  let { page, limit, userId } = req.body;
  var num = (page - 1) * limit;
  let data = await getKnowList(num, limit, {});

  let asyncList = data.data.map(item => {
    return new Promise(async (res, rej) => {
      if (userId) {
        let is_collection = await isCollection({
          userId, rticleaId: item.rticleaId
        })
        is_collection = Boolean(is_collection.length)
        item.is_collection = is_collection
      } else {
        item.is_collection = false
      }
      res()
    })
  })
  await Promise.all(asyncList)

  res.json({
    code: 1,
    data: FormatData(data.data, {
      rticleaImgList: 'json',
      rticleaTime: 'date'
    }),
    msg: '获取成功'
  })
})
/**
 * 收藏
 */
router.post('/addFollow', async (req, res, next) => {
  let { userId, rticleaId } = req.body;
  let flog = await isaaddFollow({
    userId, rticleaId
  })

  if (flog.length) {
    await delFollow(flog[0].collection)
    res.json({
      code: 1,
      data: {
        info: "取消收藏成功",
        flog: 0
      }
    })
  } else {
    await addFollow({
      userId, rticleaId
    })
    res.json({
      code: 1,
      data: {
        info: "收藏成功",
        flog: 0
      }
    })
  }
})
/**
 * 获取文章详情
 */
router.post('/knowDetail', async (req, res, next) => {
  let { rticleaId, userId } = req.body;
  let data = await knowDetail(rticleaId)
  res.json({
    code: 1,
    data: FormatData(data, {
      rticleaImgList: 'json',
      rticleaTime: 'date'
    }),
    msg: '获取成功'
  })
})
/**
 * 用户评论
 */
router.post('/addKnowComm', async (req, res, next) => {
  let { content, userId, rticleaId } = req.body
  let data = await addKnowComm({
    userId, rticleaId, comm: content
  });
  res.json({
    code: 1,
    data: data,
    msg: "添加成功"
  })
})
/**
 * 获取帖子评论
 */
router.post('/getKnowComm', async (req, res, next) => {
  let { page, limit, id } = req.body;
  var num = (page - 1) * limit;
  let data = await getKnowComm(num, limit, {
    rticleaId: id
  })
  res.json({
    code: 1,
    data: FormatData(data.data, {
      time: 'date'
    }),
    msg: '获取成功'
  })
})
/**
 * 添加帖子
 */
router.post('/addInfo', async (req, res, next) => {
  let { userId, infoTitle, infoComm, infoImgList, infoReceive, infoAddress, infoDewo, infoSterilization, infoSpecies, infoVaccines, infoType } = req.body
  let sensitiveData = await getSensitiveAll();
  let words = sensitiveData.map((item, index) => {
    return item['sensitiveTag']
  })
  var scanner = new FastScanner(words)
  var hits = scanner.hits(infoComm)
  if (JSON.stringify(hits) !== "{}") {
    let sensitiveNum = Object.keys(hits);
    return res.json({
      code: 444,
      data: sensitiveNum,
      msg: "敏感词汇"
    })
  }
  let data = await addInfo({
    userId, infoTitle, infoComm, infoImgList: JSON.stringify(infoImgList), infoReceive, infoAddress, infoDewo, infoSterilization, infoSpecies, infoVaccines, infoType
  });

  res.json({
    code: 1,
    data: data,
    msg: "添加成功"
  })
})
/**
 * 获取点赞我的帖子
 */
router.post('/getLikeList', async (req, res, next) => {
  let { page, limit, userId } = req.body;
  var num = (page - 1) * limit;
  let data = await getLikeList(num, limit, { userId: userId })
  res.json({
    code: 1,
    data: FormatData(data, {
      infoImgList: 'json',
      infoTime: 'date'
    }),
    msg: '获取成功'
  })
})
/**
 * 获取评论
 */
router.post('/getCommList', async (req, res, next) => {
  let { page, limit, userId } = req.body;
  var num = (page - 1) * limit;
  let data = await getCommList(num, limit, { userId: userId })
  res.json({
    code: 1,
    data: FormatData(data, {
      infoImgList: 'json',
      infoTime: 'date',
      time: 'date'
    }),
    msg: '获取成功'
  })
})
/**
 * 获取我的收藏
 */
router.post('/getCollectionList', async (req, res, next) => {
  let { page, limit, userId } = req.body;
  var num = (page - 1) * limit;
  let data = await getCollectionList(num, limit, { userId: userId })
  res.json({
    code: 1,
    data: FormatData(data, {
      rticleaImgList: 'json',
      rticleaTime: 'date'
    }),
    msg: '获取成功'
  })
})
/**
 * 图片文件上传处理
 */
router.post('/uploadImg', upload.single('file'), async (req, res, next) => {
  let url = `${req.protocol}://${req.headers.host}/${req.file.path}`;
  res.json({
    code: 1,
    url: urlf2z(url)
  })
})


module.exports = router;
